
package andre.grids.db;

import andre.grids.db.dataclasses.*;
import andre.grids.guids.*;
import com.db4o.*;
import java.util.Iterator;

/**
 *
 * @author andre
 */
public class DbReplicaQueries extends 
        DbQueries<DbFileReplica> {
    
    public DbPeer[] getReplicasByFileName(String fileName) {        
        DbFileQueries query = new DbFileQueries();
        DbFile file = query.getByName(fileName);
        if (file == null)
            return null;
        
        return getReplicasByDbFile(file);
    }
    
    private DbPeer[] getReplicasByDbFile(DbFile file) {
        DbFileReplica proto = new DbFileReplica();
        proto.setFile(file);
        
        ObjectSet<DbFileReplica> replicas = super.getObjectListByPrototype(proto);
        DbFileReplica[] fileReplicas = toArray(replicas);
        DbPeer [] peers = new DbPeer[fileReplicas.length];
        int x = 0;
        for(DbFileReplica r: fileReplicas) {
            super.getDb().getObjects().activate(r, 1);
            peers[x++] = r.getReplicaHost();
        }
        return peers;        
    }
    
    public DbPeer[] getReplicasByFileGuid(IGuid guid) {
        DbFileQueries query = new DbFileQueries();
        DbFile [] files = query.getByGuid(guid);        
        if (files == null)
            return null;
        
        return getReplicasByDbFile(files[0]);
    }

    
    private DbFileReplica[] toArray(ObjectSet<DbFileReplica> replicas) {
        if (replicas == null || replicas.size() == 0)
            return null;
        
        DbFileReplica[] result = new DbFileReplica[replicas.size()];
        Iterator<DbFileReplica> it = replicas.iterator();
        int x = 0;
        for(;it.hasNext();)
            result[x++] = it.next();
        return result;
    }
}
